//
//  FluView.swift
//  Runner
//
//  Created by yfwl on 2024/1/18.
//

import Foundation
import Flutter

class FluView : NSObject , FlutterPlatformView{
    
    private var binaryMessenger : FlutterBinaryMessenger
    private var num : Int? = -1
    private var sw : CGFloat
    private var sh : CGFloat
    private var txtView : UILabel
    private var viewContainer : UIView
    private var btnButton : UIButton
    
    
    init(binaryMessenger : FlutterBinaryMessenger,viewId: Int64, args: Any?) {
        self.binaryMessenger = binaryMessenger
        
        if(args != nil){
            if let arguments = args as? Dictionary<String,Any?>{
               num = arguments["num"] as? Int ?? (-1)
            }
        }
        self.sw = UIScreen.main.bounds.width
        self.sh = UIScreen.main.bounds.height
        
        self.viewContainer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.sw, height: 300))
        self.viewContainer.backgroundColor = UIColor.gray
        
        self.txtView = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: self.sw, height: 100))
        self.txtView.backgroundColor = UIColor.orange
        self.txtView.numberOfLines = 5
        self.txtView.text = "我是原生ios view，来自flutter端的参数为：\(num!)"
        
        self.btnButton = UIButton.init(frame: CGRect.init(x: 0, y: 110, width: self.sw, height: 50))
        self.btnButton.backgroundColor = UIColor.cyan
        self.btnButton.setTitle("我是原生Button，点击我向flutter端传值", for: UIControl.State.normal)
        self.viewContainer.addSubview(self.txtView)
        self.viewContainer.addSubview(self.btnButton)
    }
    
   
    func setMethodChannel(){
        var methodChannel = FlutterMethodChannel.init(name: "com.lx.FluView.methodChannel", binaryMessenger: self.binaryMessenger)
        methodChannel.setMethodCallHandler(handelMethod)
    }
    
    func handelMethod(call: FlutterMethodCall , result : FlutterResult){
        let method = call.method
        let argumentsTemp = call.arguments
        if(method == "addNum"){
            if(argumentsTemp != nil){
                if let arguments = argumentsTemp as? Dictionary<String,Any?>{
                    let numTemp = arguments["num"] as? Int ?? (-1)
                    self.txtView.text = "我是原生ios view，来自flutter端的参数为：\(numTemp)"
                }
            }
        }
    }
    
    func view() -> UIView {
        self.btnButton.addTarget(self, action: #selector(btnPost), for: UIControl.Event.touchUpInside)
        return self.viewContainer
    }
    @objc func btnPost(){
        num = num! + 1
        FlupluginPlugin.eventSink?(["num":num])
    }
    
}
